package omm.domain;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserSessionFilter implements Filter {

	private ArrayList<String> urlList;

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		String url = ((HttpServletRequest) req).getRequestURL().toString();
		String suburl = url.substring(url.lastIndexOf('/') + 1, url.length());

		if (suburl.equals("login")) {
			chain.doFilter(req, res);
		} else {
			HttpSession session = ((HttpServletRequest) req).getSession(false);
			if (session != null && session.getAttribute("user") != null) {

				if (urlList.contains(suburl)) {
					chain.doFilter(req, res);
				} else {
					((HttpServletRequest) req).getRequestDispatcher(
							"/WEB-INF/jsp/loginerror.jsp").forward(req, res);
				}
			} else {
				((HttpServletRequest) req).getRequestDispatcher(
						"/WEB-INF/jsp/loginerror.jsp").forward(req, res);
			}

		}

	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		urlList = new ArrayList<String>();
		//Lista de paginas permitidas solo con login
		urlList.add("showGeneralViewGraphics");
		urlList.add("showEvolutionViewGraphic");
		urlList.add("showComparativeViewGraphic");
		urlList.add("logout");	
		}
	

	@Override
	public void destroy() {
	}


}
